#include "bsp_flash.h"

void Flash_Write(uint32_t addr,uint32_t *data,uint32_t len){
    
    FLASH_EraseInitTypeDef eraseInitStruct;
    uint32_t PAGEError = 0;
    uint32_t flash_program_start = addr ;                                            /*Start address for flash program*/
    uint32_t flash_program_end = (addr + len);
    uint32_t *src = (uint32_t *)data;
    
    HAL_FLASH_Unlock();
    
    eraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGEERASE;
    eraseInitStruct.PageAddress = flash_program_start;
    eraseInitStruct.NbPages = len/FLASH_PAGE_SIZE+1;
    if(HAL_FLASHEx_Erase(&eraseInitStruct,&PAGEError) != HAL_OK){
        APP_ErrorHandler();
    }
    
    while(flash_program_start < flash_program_end){
        
        if(HAL_FLASH_Program(FLASH_TYPEPROGRAM_PAGE,flash_program_start,src) == HAL_OK){
            flash_program_start += FLASH_PAGE_SIZE;
            src += FLASH_PAGE_SIZE/4;
        }
    }
    HAL_FLASH_Lock();
    
}


void Flash_Read(uint32_t address,uint32_t *buff,uint32_t length){
    for(int i = 0;i<length;i++){
        buff[i] = *(volatile uint32_t *)address;
        address+=4;
    }
}

